package com.example.gulimall.seckill.config;

import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.SecKillConstant;
import com.example.common.entity.member.MemberEntity;
import com.example.common.utils.GuLiMallThreadLocalPool;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Configuration
public class LoginUserInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean ma = antPathMatcher.match(SecKillConstant.KILL_URL, uri);
        if (!ma) {
            return true;
        }

        final HttpSession session = request.getSession();
        MemberEntity memberEntity = (MemberEntity) request.getSession()
                .getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);

        // 优先检查 session，将当前用户塞到线程中
        if (Objects.nonNull(memberEntity)) {
            GuLiMallThreadLocalPool.setMember(memberEntity);
            return true;
        }
        session.setAttribute("msg", "您还未登录，请先登录!");
        response.sendRedirect("http://auth.gulimall.com/login.html");
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        GuLiMallThreadLocalPool.removeMember();
    }
}
